/*
 * 系统名称: ARES 应用快速开发企业套件
 * 模块名称: 基础业务应用
 * 类 名 称   : MenuUtil.java
 * 软件版权: 杭州恒生电子股份有限公司
 * 相关文档:
 * 修改记录:
 * 修改日期		修改人员		修改说明<BR>
 * ==========================================================
 * 
 * ==========================================================
 * 评审记录：
 * 
 * 评审人员：
 * 评审日期：
 * 发现问题：
 */
package com.hundsun.jres.bizframe.core.framework.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.hundsun.jres.bizframe.core.authority.bean.SysMenu;
import com.hundsun.jres.bizframe.core.authority.cache.BizFrameMenuCache;
import com.hundsun.jres.bizframe.core.authority.cache.UserInfo;
import com.hundsun.jres.bizframe.core.authority.cache.UserMenuCache;

/**
 * 
 * @author huhl
 * 
 */
public class MenuUtil {

	public MenuUtil() {
	}

	@SuppressWarnings("unchecked")
	public String getTopMenuFormat(HttpSession session, SysMenu menu,
			String basePath, int menuDepth) {
		UserInfo userInfo = HttpUtil.getUserInfo(session);
		List menus = new ArrayList();
		String childrenMenu = "menu:[";
		try {
			menus = userInfo.getMehuCache()
					.getChildrenCodes(menu.getMenuCode());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (menuDepth < top_menu_depth && menus.size() > 0) {
			for (int i = 0; i < menus.size(); i++) {
				SysMenu menuTemp = (SysMenu) menus.get(i);
				if (null == menuTemp)
					continue;
				String _code = menuTemp.getMenuCode().trim();
				String _name = menuTemp.getMenuName().trim();
				String menuUrl = getMenuUrl(menuTemp);
				String _url = getHttpUrl(basePath, menuUrl);
				String _icon = getMenuIconCls(menuTemp);
				String childrenMenuScriptTemp = "{id:'$menuCode$_topMenu',\n text: '$menuName$',\n iconCls:'$iconCls$',\n code:'$menuCode$',\n view_url:'$menuViewUrl$', \n menu:[$items$] \n}"
						.replace("$menuCode$", _code).replace("$menuViewUrl$",
								_url).replace("$menuName$", _name).replace(
								"$iconCls$", _icon);
				int pDepth = menuDepth + 1;
				String menuTempScript = getTopMenuFormat(session, menuTemp,
						basePath, pDepth);
				if (null == menuTempScript || "".equals(menuTempScript))
					childrenMenu = (new StringBuilder())
							.append(childrenMenu)
							.append(
									childrenMenuScriptTemp
											.replace("menu:[$items$]",
													"app:this.app,\n listeners:{click:this.createWindow }"))
							.toString();
				else
					childrenMenu = (new StringBuilder()).append(childrenMenu)
							.append(
									childrenMenuScriptTemp.replace(
											"menu:[$items$]", menuTempScript))
							.toString();
				if (i < menus.size() - 1)
					childrenMenu = (new StringBuilder()).append(childrenMenu)
							.append(",").toString();
			}

			childrenMenu = (new StringBuilder()).append(childrenMenu).append(
					"\n]").toString();
		} else {
			childrenMenu = "";
		}
		return childrenMenu;
	}

	@SuppressWarnings("unchecked")
	public String getTopMenuFormat(HttpSession session, int start,
			String basePath, List menus, int menuDepth) {
		String childrenMenu = "menu:[";
		for (int i = start; i < menus.size(); i++) {
			SysMenu menuTemp = (SysMenu) menus.get(i);
			if (null == menuTemp)
				continue;
			String _code = menuTemp.getMenuCode().trim();
			String _name = menuTemp.getMenuName().trim();
			String menuUrl = getMenuUrl(menuTemp);
			String _url = getHttpUrl(basePath, menuUrl);
			String _icon = getMenuIconCls(menuTemp);
			String childrenMenuScriptTemp = "{id:'$menuCode$_topMenu',\n text: '$menuName$',\n iconCls:'$iconCls$',\n code:'$menuCode$',\n view_url:'$menuViewUrl$', \n menu:[$items$] \n}"
					.replace("$menuCode$", _code)
					.replace("$menuViewUrl$", _url)
					.replace("$menuName$", _name).replace("$iconCls$", _icon);
			int pDepth = menuDepth + 1;
			String menuTempScript = getTopMenuFormat(session, menuTemp,
					basePath, pDepth);
			if (null == menuTempScript || "".equals(menuTempScript))
				childrenMenu = (new StringBuilder())
						.append(childrenMenu)
						.append(
								childrenMenuScriptTemp
										.replace("menu:[$items$]",
												"app:this.app,\n listeners:{click:this.createWindow }"))
						.toString();
			else
				childrenMenu = (new StringBuilder()).append(childrenMenu)
						.append(
								childrenMenuScriptTemp.replace(
										"menu:[$items$]", menuTempScript))
						.toString();
			if (i < menus.size() - 1)
				childrenMenu = (new StringBuilder()).append(childrenMenu)
						.append(",").toString();
		}

		childrenMenu = (new StringBuilder()).append(childrenMenu).append("\n]")
				.toString();
		return childrenMenu;
	}

	@SuppressWarnings("unchecked")
	public String getStartMenuFormat(HttpSession session, SysMenu menu,
			String basePath, int menuDepth) {
		UserInfo userInfo = HttpUtil.getUserInfo(session);
		List menus = new ArrayList();
		String childrenMenu = "menu:[";
		try {
			menus = userInfo.getMehuCache()
					.getChildrenCodes(menu.getMenuCode());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (menuDepth < start_menu_depth && menus.size() > 0) {
			for (int i = 0; i < menus.size(); i++) {
				SysMenu menuTemp = (SysMenu) menus.get(i);
				if (null == menuTemp)
					continue;
				String _code = menuTemp.getMenuCode().trim();
				String _name = menuTemp.getMenuName().trim();
				String menuUrl = getMenuUrl(menuTemp);
				String _url = getHttpUrl(basePath, menuUrl);
				String _icon = getMenuIconCls(menuTemp);
				String childrenMenuScriptTemp = "{id:'$menuCode$_startMenu',\n text: '$menuName$',\n iconCls:'$iconCls$',\n code:'$menuCode$',\n view_url:'$menuViewUrl$', \n menu:[$items$] \n}"
						.replace("$menuCode$", _code).replace("$menuViewUrl$",
								_url).replace("$menuName$", _name).replace(
								"$iconCls$", _icon);
				int pDepth = menuDepth + 1;
				String menuTempScript = getStartMenuFormat(session, menuTemp,
						basePath, pDepth);
				if (null == menuTempScript || "".equals(menuTempScript))
					childrenMenu = (new StringBuilder())
							.append(childrenMenu)
							.append(
									childrenMenuScriptTemp
											.replace("menu:[$items$]",
													"scope: this, \n handler : this.createWindow"))
							.toString();
				else
					childrenMenu = (new StringBuilder()).append(childrenMenu)
							.append(
									childrenMenuScriptTemp.replace(
											"menu:[$items$]", menuTempScript))
							.toString();
				if (i < menus.size() - 1)
					childrenMenu = (new StringBuilder()).append(childrenMenu)
							.append(",").toString();
			}

			childrenMenu = (new StringBuilder()).append(childrenMenu).append(
					"\t\n]").toString();
		} else {
			childrenMenu = "";
		}
		return childrenMenu;
	}

	@SuppressWarnings("unchecked")
	public String getDefaultMenuFormat(HttpSession session, SysMenu menu,
			String basePath, int menuDepth) {
		UserInfo userInfo = HttpUtil.getUserInfo(session);
		List menus = new ArrayList();
		String childrenMenu = "menu:[";
		try {
			menus = userInfo.getMehuCache()
					.getChildrenCodes(menu.getMenuCode());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (menuDepth < default_menu_depth && menus.size() > 0) {
			for (int i = 0; i < menus.size(); i++) {
				SysMenu menuTemp = (SysMenu) menus.get(i);
				if (null == menuTemp)
					continue;
				String _code = menuTemp.getMenuCode().trim();
				String _name = menuTemp.getMenuName().trim();
				String menuUrl = getMenuUrl(menuTemp);
				String _menuArg = menuTemp.getMenuArg();
				String _windowType = menuTemp.getWindowType();
				String _url = getHttpUrl(basePath, menuUrl);
				String _icon = getMenuIconCls(menuTemp);
				String childrenMenuScriptTemp = "{id:'$menuId$_menu',\n text: '$menuName$',\n url: '$menuViewUrl$',\n menuArg: '$menuArg$',\n windowType: '$windowType$',\n iconCls:'$iconCls$', \n$noLeaf_menu_hander$, \n menu:[$items$] \n}"
						.replace("$menuId$", _code)
						.replace("$menuName$", _name).replace("$menuArg$",
								_menuArg).replace("$windowType$", _windowType)
						.replace("$iconCls$", _icon).replace("$menuViewUrl$",
								_url);
				String noLeaf_menu_hander = "handler :  function(){initMenu('$menuName$','$menuId$');}"
						.replace("$menuId$", _code)
						.replace("$menuName$", _name);
				int pDepth = menuDepth + 1;
				String menuTempScript = getDefaultMenuFormat(session, menuTemp,
						basePath, pDepth);
				if (null == menuTempScript || "".equals(menuTempScript)) {
					List _menus = userInfo.getMehuCache().getChildrenCodes(
							menuTemp.getMenuCode());
					if (_menus.size() > 0) {
						childrenMenuScriptTemp = childrenMenuScriptTemp
								.replace("\n$noLeaf_menu_hander$,",
										noLeaf_menu_hander);
						childrenMenu = (new StringBuilder()).append(
								childrenMenu).append(
								childrenMenuScriptTemp.replace(
										"menu:[$items$]", "")).toString();
					} else {
						String handler = "listeners :{click:onClickMenuItem}"
								.replace("$menuViewUrl$", _url).replace(
										"$menuId$", _code).replace(
										"$menuName$", _name);
						childrenMenuScriptTemp = childrenMenuScriptTemp
								.replace("\n$noLeaf_menu_hander$,", "");
						childrenMenu = (new StringBuilder()).append(
								childrenMenu).append(
								childrenMenuScriptTemp.replace(
										"menu:[$items$]", handler)).toString();
					}
					_menus = null;
				} else {
					childrenMenuScriptTemp = childrenMenuScriptTemp.replace(
							"$noLeaf_menu_hander$", noLeaf_menu_hander);
					childrenMenu = (new StringBuilder()).append(childrenMenu)
							.append(
									childrenMenuScriptTemp.replace(
											"menu:[$items$]", menuTempScript))
							.toString();
				}
				if (i < menus.size() - 1)
					childrenMenu = (new StringBuilder()).append(childrenMenu)
							.append(",").toString();
			}

			childrenMenu = (new StringBuilder()).append(childrenMenu).append(
					"\t\n]").toString();
		} else {
			childrenMenu = "";
		}
		return childrenMenu;
	}

	public static String getMenuIconCls(SysMenu menu) {
		String menuIconCls = "icon_default";
		if (null != menu) {
			String menuIcon = menu.getMenuIcon().trim();
			if (null != menuIcon && !"".equals(menuIcon))
				menuIconCls = (new StringBuilder()).append("icon_").append(
						menu.getMenuCode().trim()).toString();
		}
		return menuIconCls;
	}

	@SuppressWarnings("unchecked")
	public static List getMenusCss(HttpSession session, String basePath) {
		List menu_css_list = new ArrayList();
		UserInfo userInfo = HttpUtil.getUserInfo(session);
		List menuCodes = userInfo.getMehuCache().getAllMenuCodes();
		userInfo.getMehuCache();
		String kindCode = UserMenuCache.getKindCode();
		BizFrameMenuCache menuCache = BizFrameMenuCache.getInstance();
		try {
			Iterator i$ = menuCodes.iterator();
			do {
				if (!i$.hasNext())
					break;
				String code = (String) i$.next();
				SysMenu menu = menuCache.getSysMenu(kindCode, code);
				if (menu != null) {
					String menuIcon = menu.getMenuIcon().trim();
					if (null != menuIcon && !"".equals(menuIcon))
						menu_css_list
								.add(".icon_$menucode$ {background-image: url($basepath$$menuIcon$ ) !important;}"
										.replace("$menuIcon$", menuIcon)
										.replace("$menucode$", code).replace(
												"$basepath$", basePath));
				}
			} while (true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return menu_css_list;
	}

	public static String getHttpUrl(String basePath, String url) {
		String res_url = "";
		if (null != url && !"".equals(url.trim()))
			if (url.trim().toLowerCase().startsWith("http://")
					|| url.trim().toLowerCase().startsWith("https://"))
				res_url = url;
			else
				res_url = (new StringBuilder()).append(basePath).append(url)
						.toString();
		return res_url;
	}

	public static String getMenuUrl(SysMenu menu) {
		String _viewUrl = menu.getMenuUrl().trim();
		String _subTransCode = menu.getSubTransCode().trim();
		String _resCode = menu.getTransCode().trim();
		String _args = menu.getMenuArg().trim();
		String _winOpenType = menu.getWindowType().trim();
		String _url = "";
		String parameters = "";
		if (!"".equals(_viewUrl) && null != _viewUrl) {
			int _index = _viewUrl.indexOf("?");
			if (_viewUrl.toLowerCase().contains(".do")) {
				if (_index > 0) {
					String _viewUrlParameter = _viewUrl.substring(_index + 1);
					parameters = _viewUrlParameter;
					_viewUrl = _viewUrl.substring(0, _index);
				}
			} else if (_index > 0) {
				String _viewUrlParameter = _viewUrl.substring(_index + 1);
				parameters = (new StringBuilder()).append(_viewUrlParameter)
						.append("&opCode=").append(_subTransCode).append(
								"&resCode=").append(_resCode).toString();
				_viewUrl = _viewUrl.substring(0, _index);
			} else {
				parameters = (new StringBuilder()).append("opCode=").append(
						_subTransCode).append("&resCode=").append(_resCode)
						.toString();
			}
			if (null != _args && !"".equals(_args))
				if ("".equals(parameters))
					parameters = (new StringBuilder()).append(parameters)
							.append(_args).toString();
				else
					parameters = (new StringBuilder()).append(parameters)
							.append("&").append(_args).toString();
			if (null != _winOpenType && !"".equals(_winOpenType)) {
				String _openWin = (new StringBuilder()).append("winOpen=")
						.append(_winOpenType).toString();
				if ("".equals(parameters))
					parameters = (new StringBuilder()).append(parameters)
							.append(_openWin).toString();
				else
					parameters = (new StringBuilder()).append(parameters)
							.append("&").append(_openWin).toString();
			}
			_url = (new StringBuilder()).append(_viewUrl).append("?").append(
					parameters).toString();
		}
		return _url;
	}

	@SuppressWarnings("unused")
	private static int getMenuDepth(SysMenu menu) {
		String treeIndex = menu.getTreeIdx();
		int depth = getCharNumInString(treeIndex, '#');
		depth = depth <= 3 ? 0 : depth - 3;
		return depth;
	}

	private static int getCharNumInString(String str, char cha) {
		char chars[] = str.toCharArray();
		int i = 0;
		char arr$[] = chars;
		int len$ = arr$.length;
		for (int i$ = 0; i$ < len$; i$++) {
			char c = arr$[i$];
			if (c == cha)
				i++;
		}

		return i;
	}

	public static synchronized String productMenuTreeIdx(String kindCode,
			String menuCode) {
		if (null == kindCode || "".equals(kindCode.trim()))
			throw new IllegalArgumentException(
					"kindCode must not be null and ''");
		if (null == menuCode || "".equals(menuCode.trim()))
			throw new IllegalArgumentException(
					"menuCode  must not be null and '' ");
		String treeIdex = "";
		BizFrameMenuCache cache = BizFrameMenuCache.getInstance();
		if (menuCode.equals("bizroot"))
			return (new StringBuilder()).append("#").append(menuCode).append(
					"#").toString();
		SysMenu menu = cache.getSysMenu(kindCode, menuCode);
		if (menu == null) {
			return (new StringBuilder()).append("#").append(menuCode).append(
					"#").toString();
		} else {
			String parentCode = menu.getParentCode();
			treeIdex = (new StringBuilder()).append(
					productMenuTreeIdx(kindCode, parentCode)).append(menuCode)
					.append("#").toString();
			return treeIdex;
		}
	}

	public static int top_menu_depth = 2147483647;
	public static int start_menu_depth = 2147483647;
	public static int default_menu_depth = 2147483647;
	static final String top_menu_menu = "{id:'$menuCode$_topMenu',\n text: '$menuName$',\n iconCls:'$iconCls$',\n code:'$menuCode$',\n view_url:'$menuViewUrl$', \n menu:[$items$] \n}";
	static final String top_menu_handler = "app:this.app,\n listeners:{click:this.createWindow }";
	static final String start_menu_menu = "{id:'$menuCode$_startMenu',\n text: '$menuName$',\n iconCls:'$iconCls$',\n code:'$menuCode$',\n view_url:'$menuViewUrl$', \n menu:[$items$] \n}";
	static final String start_menu_handler = "scope: this, \n handler : this.createWindow";
	static final String default_menu = "{id:'$menuId$_menu',\n text: '$menuName$',\n url: '$menuViewUrl$',\n iconCls:'$iconCls$', \n$noLeaf_menu_hander$, \n menu:[$items$] \n}";
	static final String default_noLeaf_menu_hander = "handler :  function(){initMenu('$menuName$','$menuId$');}";
	static final String default_menu_handler = "listeners :{click:onClickMenuItem}";
	static final String menu_css_temp = ".icon_$menucode$ {background-image: url($basepath$$menuIcon$ ) !important;}";

	static {
		int default_depth = SysParameterUtil.getIntProperty(
				"default_menu_depth", 0);
		int start_depth = SysParameterUtil.getIntProperty(
				"desktop_start_menu_depth", 0);
		int top_depth = SysParameterUtil.getIntProperty(
				"desktop_navigation_menu_depth", 0);
		default_menu_depth = default_depth > 0 ? default_depth : 2147483647;
		start_menu_depth = start_depth > 0 ? start_depth : 2147483647;
		top_menu_depth = top_depth > 2 ? top_depth : 2147483647;
	}
}
